import Sequelize from 'sequelize';
import express from 'express';
import { statusList, sequelizeStatus } from '../../common/status'; // 状态码对照
import { Item, Sku } from '../../modal/index'; // 数据库实体类
import { checkPermission, toString } from '../../utils/utils'; // 工具类

const router = express.Router();
const permission = ["all"];

router.post('/', async function (Request, Response, next) {
  // Item.Modal.sync()
  //权限校验
  await checkPermission(Request, Response, permission)
  let param = Request.body;
  let itemId = param.id;
  let skus = toString(param.skus, ["skuAttr"]);
  Item.Modal.update(param, {
    where: {
      id: itemId,
    }
  }).then(res => {
    if (res && res[0] > 0) {
      // 更新商品Item信息成功，继续更新商品SKU信息
      console.log('更新商品Item成功')
      skus.forEach(async sku => {
        if (sku.delete) {
          // 如果是删除SKU
          await deleteSku(sku, Response)
        } else {
          if (sku.id) {
            // 存在ID则为更新
            await updateSku(sku, Response)
          } else {
            // 不存在ID新增SKU
            await addSku(sku, Response)
          }
        }
        // 保存成功
        Response.json({
          data: "",
          message: "success"
        });
      });
    } else {
      Response.status(300).send({ message: "商品查询失败" });
    }
  }).catch(err => {
    console.log(err)
    Response.status(500).send({ message: sequelizeStatus[err.name] || statusList[500] || err.name });
  });
});

function updateSku(sku, Response) {
  // 更新sku
  return new Promise((resolve, reject) => {
    Sku.Modal.update(sku, {
      where: {
        id: sku.id,
      }
    }).then(res => {
      if (res && res[0] > 0) {
        // 更新sku成功
        resolve('access')
      } else {
        Response.status(300).send({ message: "商品查询失败" });
      }
    }).catch(err => {
      console.log(err)
      Response.status(500).send({ message: sequelizeStatus[err.name] || statusList[500] || err.name });
    });
  })
}

function addSku(sku, Response) {
  // 新增sku
  return new Promise((resolve, reject) => {
    Sku.Modal.create(sku).then(res => {
      if (res && res.id) {
        // 插入sku成功
        resolve('access')
      } else {
        Response.status(300).send({ message: "商品查询失败" });
      }
    }).catch(err => {
      console.log(err)
      Response.status(500).send({ message: sequelizeStatus[err.name] || statusList[500] || err.name });
    });
  })
}

function deleteSku(sku, Response) {
  // 更新sku
  return new Promise((resolve, reject) => {
    Sku.Modal.destroy({
      where: {
        id: sku.id,
      }
    }).then(res => {
      if (res && res > 0) {
        // 删除sku成功
        resolve('access')
      } else {
        Response.status(300).send({ message: "商品查询失败" });
      }
    }).catch(err => {
      console.log(err)
      Response.status(500).send({ message: sequelizeStatus[err.name] || statusList[500] || err.name });
    });
  })
}

module.exports = router;
  // 创建新记录
  // for (let i = 0; i <= 50; i++) {
  //     Item.Modal.create(
  //     {
  //       itemName: "雪佛兰护肤保湿凝胶补血颗粒" + String(i),
  //       itemShelf: 0,
  //       itemMainImg: "https://logistics-2b-dev.oss-cn-hangzhou.aliyuncs.com/wahaha.jpg",
  //       price: 18.24,
  //     }
  //   );
  // }
  //  for (let i = 0; i <= 3; i++) {
  //   Sku.Modal.create(
  //     {
  //       skuName: "颜色",
  //       skuAtt: "白色" + String(i),
  //       itemId: 5,
  //       stockQuantity: 18 + i,
  //       price: 12.18 + i,
  //       outCode: "ZRWANFK013" + String(i),
  //     }
  //   );
  // }